import json
import traceback

from flask import Flask, current_app
from flask.json import jsonify

from app.extensions import db
from app.views import index_bp
from werkzeug.exceptions import UnprocessableEntity


def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///chatgpt.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)
    with app.app_context():
        db.create_all()

    configure_blueprints(app)

    configure_error_handlers(app)

    return app


def configure_blueprints(app):
    from app.views import index_bp

    app.register_blueprint(index_bp, url_prefix="/")


def configure_error_handlers(app):
    @app.errorhandler(UnprocessableEntity)
    def handle_unprocessable_entity(e):
        if not hasattr(e, "data"):
            desc = e.description
        else:
            messages = e.data.get("messages")
            desc = messages.get("json", messages.get("query", messages.get("form", messages.get("files", {}))))

        return jsonify({"status": e.code, "msg": json.dumps(desc, ensure_ascii=False)}), e.code

    @app.errorhandler(401)
    @app.errorhandler(400)
    def handle_400_error(error):
        return jsonify({"code": error.code, "msg": error.description}), error.code

    @app.errorhandler(500)
    def handle_http(error):
        current_app.logger.error(traceback.format_exc())
        return jsonify(**{"code": "500", "msg": str(error)}), 500
